package com.sevennotes.classtable.ui.pages.tablelist

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.CutCornerShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.SoftwareKeyboardController
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.sevennotes.classtable.model.TableName
import com.sevennotes.classtable.ui.pages.components.ConfirmAndCancelButtons
import com.sevennotes.classtable.ui.pages.components.MyAddFloatingButton
import com.sevennotes.classtable.ui.pages.components.SimpleComfirmDialog
import com.sevennotes.classtable.ui.pages.main_screen.MainScreenPad
import com.sevennotes.classtable.ui.pages.main_screen.MainViewModel
import com.sevennotes.classtable.ui.pages.main_screen.TableNameListState

private enum class DialogType {
  ADD_DIALOG, CONFIRM_DIALOG, EDIT_NAME_DIALOG
}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun TableNameScreen(
  titleText: @Composable (String) -> Unit,
  goBackButton: @Composable () -> Unit,
  tableNameListState: TableNameListState,
  addTableName: (TableName) -> Unit,
  changeTableName: (TableName) -> Unit,
  copyClasses: (Int) -> Unit,
  onTableNameSelect: (TableName) -> Unit,// { mainScreenViewModel.changeCurrentTable(it.id!!) },
  onDeleteTableName: (TableName) -> Unit,
) {

  var showAddDialog by remember { mutableStateOf(false) }
  var dialogType by remember { mutableStateOf(DialogType.ADD_DIALOG) }
  val tableNameList by tableNameListState.tableNames!!.observeAsState()
  var needChangeTN by remember { mutableStateOf(tableNameListState.currentTable) }

  if (showAddDialog) {
    var tableName by remember { mutableStateOf(TableName()) }
    when (dialogType) {
      DialogType.ADD_DIALOG -> {
        AddDialog(
          tableName = "新课表",
          onAddClick = {
            tableName = TableName(name = it)
            dialogType = DialogType.CONFIRM_DIALOG
          },
          onCancelClick = { showAddDialog = false }
        )
      }
      DialogType.CONFIRM_DIALOG -> {
        ConfirmDialog(
          tableNameList = tableNameList ?: emptyList(),
          onConfirmClick = {
            addTableName(tableName)
            it?.let { copyClasses(it) }
            showAddDialog = false
          },
          onCancelClick = { showAddDialog = false }
        )
      }
      DialogType.EDIT_NAME_DIALOG -> {
        AddDialog(
          tableName = "",
          onAddClick = {
            changeTableName(
              TableName(
                id = needChangeTN,
                name = it
              )
            )
            showAddDialog = false
          },
          onCancelClick = { showAddDialog = false }
        )
      }
    }
  }

  MainScreenPad(
    tittle = { titleText("课表管理") },
    navigationIcon = { goBackButton() },
    actions = {
      IconButton(onClick = {
        tableNameListState.editable.value = !tableNameListState.editable.value
      }) {
        Icon(imageVector = Icons.Filled.Edit, contentDescription = "edit")
      }
    },
    floatingActionButton = {
      MyAddFloatingButton {
        dialogType = DialogType.ADD_DIALOG
        showAddDialog = true
      }
    }
  ) {
    TableNameList(
      tableNameList = tableNameList,
      editable = tableNameListState.editable.value,
      currentTable = tableNameListState.currentTable,
      onTableNameSelect = onTableNameSelect,// { mainScreenViewModel.changeCurrentTable(it.id!!) },
      onDeleteTableName = onDeleteTableName,// mainScreenViewModel::deleteTableName,
      onEdit = { item ->
        needChangeTN = item.id!!
        dialogType = DialogType.EDIT_NAME_DIALOG
        showAddDialog = true
      }
    )
  }
}


@Composable
fun TableNameList(
  editable: Boolean,
  currentTable: Int,
  tableNameList: List<TableName>?,
  onTableNameSelect: (TableName) -> Unit,
  onDeleteTableName: (TableName) -> Unit,
  onEdit: (TableName) -> Unit
) {

  Column(
    modifier = Modifier.fillMaxSize(),
    horizontalAlignment = Alignment.CenterHorizontally
  ) {
    Spacer(modifier = Modifier.height(10.dp))
    LazyColumn {
      tableNameList?.let { it ->
        items(it) { item ->
          var showC by remember { mutableStateOf(false) }
          if (showC) {
            SimpleComfirmDialog(text = "确定要删除吗?", onConfirmClick = {
              onDeleteTableName(item)
              showC = false
            }) {
              showC = false
            }
          }
          TableNameItem(
            tableName = item,
            editable = editable,//
            isSelected = item.id == currentTable,//
            canBeDeleted = it.size > 1,
            onDelete = { showC = true },
            onSelect = { onTableNameSelect(item) },
            onEdit = { onEdit(item) }
          )
        }
      }
    }
  }
}

@Composable
fun TableNameItem(
  tableName: TableName,
  editable: Boolean,
  isSelected: Boolean,
  canBeDeleted: Boolean,
  onDelete: () -> Unit = {},
  onSelect: () -> Unit = {},
  onEdit: () -> Unit = {}
) {
  Row(
    modifier = Modifier.height(60.dp),
    verticalAlignment = Alignment.CenterVertically
  ) {
    AnimatedVisibility(editable) {
      Row {
        IconButton(enabled = canBeDeleted, onClick = onDelete) {
          Icon(imageVector = Icons.Filled.Delete, contentDescription = "delete")
        }
        IconButton(onClick = { onEdit() }) {
          Icon(imageVector = Icons.Filled.Edit, contentDescription = "edit")
        }
      }
    }
    if (!editable) {
      Spacer(modifier = Modifier.width(10.dp))
    }
    Text(text = tableName.name, modifier = Modifier.weight(1f))
    RadioButton(selected = isSelected, onClick = { onSelect() })
    Spacer(modifier = Modifier.width(10.dp))
  }
}

@Composable
fun ConfirmDialog(
  tableNameList: List<TableName>,
  onConfirmClick: (Int?) -> Unit,
  onCancelClick: () -> Unit
) {
  var choice by remember { mutableStateOf(TableName(name = "无")) }
  var menuOpen by remember { mutableStateOf(false) }

  AlertDialog(
    onDismissRequest = { onCancelClick() },
    buttons = {
      ConfirmAndCancelButtons(
        onConfirmClick = { onConfirmClick(choice.id) },
        onCancelClick = onCancelClick
      )
    },
    title = { Text(text = "从其他课表复制课程:") },
    text = {
      TextField(
        value = choice.name,
        onValueChange = {},
        readOnly = true,
        trailingIcon = {
          IconButton(onClick = { menuOpen = true }) {
            Icon(
              imageVector = Icons.Filled.KeyboardArrowDown,
              contentDescription = "items"
            )
          }
        }
      )
      DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = !menuOpen }) {
        tableNameList.forEach { tableName ->
          DropdownMenuItem(onClick = {
            choice = tableName
            menuOpen = false
          }) {
            Text(text = tableName.name)
          }
        }
      }
    }
  )
}

@Composable
fun AddDialog(
  tableName: String,
  onAddClick: (String) -> Unit,
  onCancelClick: () -> Unit
) {
  var name by remember { mutableStateOf(tableName) }
  AlertDialog(
    onDismissRequest = { onCancelClick() },
    buttons = {
      ConfirmAndCancelButtons(
        onConfirmClick = { onAddClick(name) },
        onCancelClick = onCancelClick
      )
    },
    title = { Text(text = "课表名称:") },
    text = { TextField(value = name, onValueChange = { name = it }) }
  )
}

@Preview
@Composable
fun TableNameItemPreview() {
  Column {
    TableNameItem(
      tableName = TableName(name = "课表1"),
      editable = true,
      isSelected = true,
      canBeDeleted = true
    )
    TableNameItem(
      tableName = TableName(name = "课表2"),
      editable = true,
      isSelected = false,
      canBeDeleted = true
    )
    TableNameItem(
      tableName = TableName(name = "课表3"),
      editable = false,
      isSelected = false,
      canBeDeleted = true
    )
    TableNameItem(
      tableName = TableName(name = "课表4"),
      editable = true,
      isSelected = false,
      canBeDeleted = true
    )
  }
}